package me.magicall.web.simple.spring.interceptors;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.magicall.util.ArrayUtil;
import me.magicall.util.kit.Kits;
import me.magicall.web.simple.spring.util.C;

import org.springframework.core.Ordered;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 对request中的请求参数进行预处理。按照以下准则：
 * 值数组无元素（非null）者认为是true；
 * 值数组仅有一个元素者认为是单值；
 * 其余情况认为值是数组或列表
 * 
 * @author MaGiCalL
 */
public class ParameterPreHandleInterceptor extends HandlerInterceptorAdapter implements Ordered {

	@Override
	public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
		final Map<String, String[]> parameterMap = request.getParameterMap();
		final Map<String, Object> finalParamMap = new HashMap<String, Object>(parameterMap.size());
		for (final Entry<String, String[]> e : parameterMap.entrySet()) {
			final String key = e.getKey();
			final String[] value = e.getValue();
			if (ArrayUtil.isEmpty(value)) {
				finalParamMap.put(key, true);
			} else if (value.length == 1) {
				final String v = value[0];
				if (!Kits.STR.isEmpty(v)) {
					if (v.equalsIgnoreCase("true")) {
						finalParamMap.put(key, true);
					} else if (v.equalsIgnoreCase("false")) {
						finalParamMap.put(key, false);
					} else if (!v.equalsIgnoreCase("null")) {
						finalParamMap.put(key, v);
					}
				}
			} else {
				final String[] vs = new String[value.length];
				int i = 0;
				for (final String v : value) {
					vs[i] = v;//FIXME 处理文字中的符号
					++i;
				}
				finalParamMap.put(key, vs);
			}
		}
		request.setAttribute(C.REQUEST_PARAMS_NAME, finalParamMap);
		request.setAttribute("requestParamsName", C.REQUEST_PARAMS_NAME);

		return true;
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
